import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_presentation/custom_model.dart';
import 'package:flutter_presentation/flutter_presentation.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  List<Map<String, dynamic>> _displayInfo =
      []; // Add state variable for display info
  final _flutterPresentationPlugin = FlutterPresentation();
  String _errorMessage = ''; // 错误信息
  int? _activeDisplayId; // 当前激活的显示设备ID

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _flutterPresentationPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () async {
                  setState(() {
                    _errorMessage = '';
                  });

                  try {
                    await _flutterPresentationPlugin.startSubScreen(
                      CustomModel(
                        payAmt: "69.00",
                        payable: "23.00",
                        needAmt: "9.00",
                        fullScreen: false,
                        products: [
                          Product("农夫山泉", "2.00", 3),
                          Product("恰恰原味瓜子", "13.00", 1),
                        ],
                        ads: [
                          Ad(
                            type: Ad.TYPE_IMAGE,
                            url:
                                "https://t7.baidu.com/it/u=2537132411,3912460994&fm=193&f=GIF",
                          ),
                          Ad(
                            type: Ad.TYPE_IMAGE,
                            url:
                                "https://t7.baidu.com/it/u=1280638388,4029210594&fm=193&f=GIF",
                          ),
                        ],
                      ),
                    );

                    setState(() {
                      _activeDisplayId = null; // 使用默认显示设备，清除之前选择的设备
                    });
                  } on PlatformException catch (e) {
                    setState(() {
                      _errorMessage = '打开副屏失败: ${e.message}';
                    });
                  } catch (e) {
                    setState(() {
                      _errorMessage = '打开副屏失败: $e';
                    });
                  }
                },
                child: const Text("打开副屏"),
              ),
              ElevatedButton(
                  onPressed: () async {
                    setState(() {
                      _errorMessage = '';
                    });

                    try {
                      await _flutterPresentationPlugin.loadData(
                        CustomModel(
                          payAmt: "123.00",
                          payable: "98.00",
                          needAmt: "19.00",
                          fullScreen: false,
                          products: [
                            Product("农夫山泉", "2.00", 30),
                            Product("恰恰原味瓜子", "19.00", 15),
                          ],
                          ads: [

                          ],
                        ),
                      );
                    } on PlatformException catch (e) {
                      setState(() {
                        _errorMessage = '更新数据失败: ${e.message}';
                      });
                    } catch (e) {
                      setState(() {
                        _errorMessage = '更新数据失败: $e';
                      });
                    }
                  },
                  child: const Text("更新数据")),
              ElevatedButton(
                onPressed: () async {
                  setState(() {
                    _errorMessage = '';
                  });
                  try {
                    final displays =
                        await _flutterPresentationPlugin.getDisplays();
                    print(displays);
                    setState(() {
                      _displayInfo = displays;
                    });
                  } on PlatformException catch (e) {
                    print("Failed to get displays: '${e.message}'.");
                    setState(() {
                      _displayInfo = []; // Clear or handle error state
                      _errorMessage = '获取设备列表失败: ${e.message}';
                    });
                  }
                },
                child: const Text("获取设备列表"),
              ),
              // 显示错误信息
              if (_errorMessage.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(_errorMessage,
                      style: const TextStyle(color: Colors.red)),
                ),
              // Add a section to display the display info
              Expanded(
                child: ListView.builder(
                  itemCount: _displayInfo.length,
                  itemBuilder: (context, index) {
                    final display = _displayInfo[index];
                    final int displayId = display['displayId'] as int;
                    final bool isActive = _activeDisplayId == displayId;

                    return Card(
                      elevation: isActive ? 4 : 1,
                      color: isActive ? Colors.blue.shade50 : null,
                      margin: const EdgeInsets.symmetric(
                          vertical: 4, horizontal: 8),
                      child: ListTile(
                        title: Text(display['name'] ?? 'Unknown Name'),
                        subtitle: Text('Display ID: $displayId'),
                        trailing: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: isActive ? Colors.green : null,
                          ),
                          onPressed: () async {
                            // 使用指定的displayId打开副屏
                            setState(() {
                              _errorMessage = '';
                            });

                            try {
                              await _flutterPresentationPlugin
                                  .startSubScreenWithDisplayId(
                                CustomModel(
                                  payAmt: "69.00",
                                  payable: "23.00",
                                  needAmt: "9.00",
                                  fullScreen: false,
                                  products: [
                                    Product("农夫山泉", "2.00", 3),
                                    Product("恰恰原味瓜子", "13.00", 1),
                                  ],
                                  ads: [
                                    Ad(
                                        type: Ad.TYPE_IMAGE,
                                        url:
                                            "https://t7.baidu.com/it/u=2537132411,3912460994&fm=193&f=GIF"),
                                    Ad(
                                        type: Ad.TYPE_IMAGE,
                                        url:
                                            "https://t7.baidu.com/it/u=1280638388,4029210594&fm=193&f=GIF"),
                                  ],
                                ),
                                displayId,
                              );

                              setState(() {
                                _activeDisplayId = displayId;
                              });
                              print("激活设备");
                            } on PlatformException catch (e) {
                              setState(() {
                                _errorMessage = '打开副屏失败: ${e.message}';
                              });
                            } catch (e) {
                              setState(() {
                                _errorMessage = '打开副屏失败: $e';
                              });
                            }
                          },
                          child: Text(isActive ? "当前已激活" : "在此设备打开"),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
